package org.example;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Timer;
import java.util.TimerTask;

// 警报状态
public class AlertState implements GameState {
    private final CodeRebirthGame game;
    private String alertText = "警告! 系统检测到异常操作! 主神正在接近!";
    private String displayedText = "";
    private int charIndex = 0;
    private Timer textTimer;

    public AlertState(CodeRebirthGame game) {
        this.game = game;
    }

    @Override
    public void enter() {
        game.setLayout(new BorderLayout());
        game.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                game.changeState(new DistractState(game));
            }
        });

        // 文字逐个显示效果
        textTimer = new Timer();
        textTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (charIndex < alertText.length()) {
                    displayedText += alertText.charAt(charIndex);
                    charIndex++;
                    game.repaint();
                } else {
                    this.cancel();
                }
            }
        }, 0, 100);
    }

    @Override
    public void render(Graphics g) {
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, game.getWidth(), game.getHeight());

        // 绘制红色三角形
        Graphics2D g2d = (Graphics2D)g;
        g2d.setColor(Color.RED);
        g2d.setStroke(new BasicStroke(5));

        int[] xPoints = {game.getWidth()/2, game.getWidth()/2 - 150, game.getWidth()/2 + 150};
        int[] yPoints = {game.getHeight()/2 - 150, game.getHeight()/2 + 150, game.getHeight()/2 + 150};
        g2d.drawPolygon(xPoints, yPoints, 3);

        // 绘制感叹号
        g2d.fillRect(game.getWidth()/2 - 10, game.getHeight()/2 - 100, 20, 80);
        g2d.fillOval(game.getWidth()/2 - 10, game.getHeight()/2 + 10, 20, 20);

        // 绘制警告文字
        g2d.setColor(Color.RED);
        g2d.setFont(game.getResourceManager().getFont("title", 24f));

        FontMetrics fm = g2d.getFontMetrics();
        int textWidth = fm.stringWidth(displayedText);
        g2d.drawString(displayedText, (game.getWidth()-textWidth)/2, game.getHeight()/2 + 200);
    }

    @Override public void update() {}

    @Override
    public void exit() {
        if (textTimer != null) textTimer.cancel();
        game.getContentPane().removeAll();
    }

    @Override public void handleInput(KeyEvent e) {}
}